library OnDoubleClick initializer init
//******************************************************
//* OnDoubleClick
//* -------------
//*  Calls a function when a player does a double click
//*
//*  Usage:
//*      call OnDoubleClick( function_name )
//*
//*  The function must take a player as first argument
//* and unit as second argument, ie:
//*
//*  function function_name takes player clickingPlayer, unit clickedUnit returns nothing
//*
//*
//********************************************************


//====================================================================================
 globals
    // The interval between clicks must be smaller than WAIT_TIME for them to count
    private constant real WAIT_TIME = 1.0
 endglobals

 //=====================================================================================
 globals
    private constant integer HUMAN_PLAYERS = 12
    private constant real EXAGGERATED_GAME_LENGTH = 1000000.0
    private timer T

    private OnDoubleClickListener array listener
    private integer listeners = 0
 endglobals

 function interface OnDoubleClickListener takes player clickingPlayer, unit clickedUnit returns nothing

 function OnDoubleClick takes OnDoubleClickListener od returns nothing
     set listener[listeners] = od
     set listeners = listeners + 1
 endfunction

 private struct Playor extends array [HUMAN_PLAYERS]
    unit lastClickUnit
    real lastClick
 endstruct


 private function onSelected takes nothing returns nothing
  local player     p  = GetTriggerPlayer()
  local Playor d  = Playor[GetPlayerId(p ) ]
  local real       now= TimerGetElapsed(T)
  local unit       u  = GetTriggerUnit()
  local integer    i
     if (d.lastClick + WAIT_TIME >= now)  and (d.lastClickUnit == u) then
         // double click!!11
         set i=0
         loop
             exitwhen (i==listeners)
             call listener[i].evaluate(p,u)
             set i=i+1
         endloop
         set d.lastClick = -WAIT_TIME
     else
         set d.lastClick = now
         set d.lastClickUnit = u
     endif

  set p=null
  set u=null
 endfunction

 private function init takes nothing returns nothing
  local integer i=0
  local trigger tr=CreateTrigger()
    loop
        exitwhen (i==HUMAN_PLAYERS)
        call TriggerRegisterPlayerUnitEvent(tr, Player(i), EVENT_PLAYER_UNIT_SELECTED, null)
        set Playor[i].lastClick = -WAIT_TIME
        set i=i+1
    endloop

    call TriggerAddAction(tr, function onSelected)
    set T=CreateTimer()
    call TimerStart(T, EXAGGERATED_GAME_LENGTH, false, null)
    set tr=null
 endfunction


endlibrary
